﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using Microsoft.Exchange.WebServices.Auth;
using Microsoft.Exchange.WebServices;


using System.Collections.ObjectModel;
using System.Net;
using System.Security;
using Microsoft.Exchange.WebServices.Data;
using System.Data;
using System.Xml;
using System.Text;
using System.Web.Configuration;


namespace UCWebpart
{
    /// <summary>
    /// getState 的摘要说明
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // 若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务，请取消注释以下行。 
    // [System.Web.Script.Services.ScriptService]
    public class SetState1 : System.Web.Services.WebService
    {
        /// <summary>
        /// 通过审批
        /// </summary>
        /// <param name="bookingId">预定编号</param>
        public void Pass(string bookingId,string reason)
        {
            var mtr = new meetingroomManagementEntities();
            var cls = (from bm in mtr.MTR_bas_BookingManage
                       where bm.bookingID == bookingId
                       select bm).SingleOrDefault<MTR_bas_BookingManage>();
            cls.bookingState = 2;//状态改为2 意味着通过审批
            //cls.cancelPerson = "";//取消的人
            //cls.cancelReason = "";//取消的原因
            string participate = cls.participants;
            cls.bookingType = "通过审批";
            //cls.cancelTime = DateTime.Now;
            mtr.SaveChanges();
        }

        /// <summary>
        /// 未通过审批
        /// </summary>
        /// <param name="bookingId"></param>
        public void Refuse(string bookingId, string reason)
        {
            var mtr = new meetingroomManagementEntities();
            var cls = (from bm in mtr.MTR_bas_BookingManage
                       where bm.bookingID == bookingId
                       select bm).SingleOrDefault<MTR_bas_BookingManage>();
            cls.bookingState = 5;//状态改为5 意味着审核没有通过
            cls.bookingType = "未通过审批";
            //cls.cancelPerson = "";//取消的人
            //cls.cancelReason = "";//取消的原因
            //cls.cancelTime = DateTime.Now;
            mtr.SaveChanges();
        }

        public WFStatus getIDAndStatus(string xml)
        {
            WFStatus ws = new WFStatus();
            XmlDocument doc = new XmlDocument();
            doc.Load(new System.IO.MemoryStream(ASCIIEncoding.Unicode.GetBytes(xml)));
            XmlElement root = null;
            root = doc.DocumentElement;
            XmlNodeList listNodes = null;
            ws.id = root.Attributes["InstanceId"].InnerText;
            listNodes = root.SelectNodes("/XMLStatus/Flows");
            foreach (XmlNode node in listNodes)
            {
                ws.status = node.Attributes["Status"].InnerText;
                break;
            }
            return ws;
        }
        /// <summary>
        /// 回传审批流结果
        /// </summary>
        /// <param name="guid">审批流的guid</param>
        /// <param name="status">最后的审批结果（通过审批或是被拒绝）</param>
        /// <param name="reason">若审批被拒绝，拒绝的原因</param>
        [WebMethod]
        public void updateVenueStatueByApprove(string guid, string status, string reason)
        {
            WFStatus ws = new WFStatus();
            ws.id = guid;
            ws.status = status;
            ws.reason = reason;
            //WFStatus ws = getIDAndStatus(xml);
            string conn = WebConfigurationManager.ConnectionStrings["meetingroomManagementConnectionString"].ConnectionString;//"Data Source=mesdbsrv.gwkf.cn;Initial Catalog=VenueBooking;User ID=vbuser;Password=vb_2013";
            string sqlquery = string.Format(@" select * from [VenueBooking].[dbo].[MTR_bas_BookingManage] bm,[VenueBooking].[dbo].MTR_bas_BookingSchedul bs,[VenueBooking].[dbo].MTR_bas_Meetingroom m 
                where bs.planId = bm.bookingID and bm.Meetingroom = m.mtrId and bm.undefine3='{0}'", ws.id);
            DataTable dt = Worker.GetDataSet(sqlquery, conn).Tables[0];
            string meetingTheme = dt.Rows[0]["meetingTheme"].ToString();
            string userName = dt.Rows[0]["bookingPerson"].ToString();
            if (ws.status == "已完成")
            {
                string startDate = dt.Rows[0]["meetingStartDate"].ToString().Split(' ')[0];
                string st = dt.Rows[0]["startTime"].ToString();
                string endDate = dt.Rows[0]["meetingEndDate"].ToString().Split(' ')[0];
                string et = dt.Rows[0]["endTime"].ToString();
                DateTime startTime = DateTime.Parse(startDate + " " + st);
                DateTime endTime = DateTime.Parse(endDate + " " + et);
                string address = dt.Rows[0]["mtrAddress"].ToString() + dt.Rows[0]["mtrAddress1"].ToString();

                string meetingAbstract = dt.Rows[0]["meetingAbstract"].ToString();
                string participants = dt.Rows[0]["participants"].ToString();
                string ccs = dt.Rows[0]["undefine3"].ToString();
                string[] attendees = participants.Split(';');
                string[] cc = ccs.Split(';');
                string keyId = dt.Rows[0]["bookingID"].ToString();

                Worker w = new Worker();
                w.SendMeetingRequest(startTime, endTime, address, meetingTheme, meetingAbstract, attendees,cc,
                    keyId, false, userName, userName + "@kaifa.cn", false, "");
                string strSql = string.Format(@"update [VenueBooking].[dbo].[MTR_bas_BookingManage] set bookingType = '{0}' ,bookingState = 2 where undefine3 = '{1}'", ws.status, ws.id);
                Worker.doSql(strSql, conn);
            }
            else if (ws.status == "已拒绝")
            {
                string mailSub = "审批拒绝提醒";
                string mailBody = "您的主题为" + meetingTheme + "的活动未通过审批,原因如下："+ws.reason;
                //Worker w = new Worker();
                Worker.sendEmailMessage(userName + "@kaifa.cn", mailSub, "venueAdmin@kaifa.cn", mailBody);
                string strSql = "update [VenueBooking].[dbo].[MTR_bas_BookingManage] set bookingType = '未通过审批' ,bookingState = 5 where undefine3 = '" + ws.id + "'";

                Worker.doSql(strSql, conn);
            }
            else
            {
                //string strSql = string.Format(@"update [VenueBooking].[dbo].[MTR_bas_BookingManage] set bookingType = '{0}' ,bookingState = 1 where undefine3 = '{1}'", ws.status, ws.id);
                //Work.doSql(strSql, conn);
            }
        }

       
        public class WFStatus
        {
            public string status { get; set; }
            public string id { get; set; }
            public string reason { get; set; }
        }
    }
}
